<template>
    <div class="tag-container">
        <!-- 查询表单 -->
        <div class="query-form-container">
            <el-form :inline="true" :model="queryInputModel" label-width="80px">

                <el-form-item label="编码:" prop="code">
                    <el-input v-model="queryInputModel.code" placeholder="请输入编码" clearable
                        style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item label="名称:" prop="name">
                    <el-input v-model="queryInputModel.name" placeholder="请输入名称" clearable
                        style="width: 150px"></el-input>
                </el-form-item>

                <el-form-item label="是否启用:" prop="status">
                    <dictselection v-model="queryInputModel.status" clearable style="width: 150px"
                        classCode="system:Status" :dictData="statsDic">
                    </dictselection>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="Search" @click="refreshHandler">查询</el-button>
                    <el-button icon="Delete" @click="resetQueryInputHandler">清空</el-button>
                </el-form-item>
            </el-form>
        </div>



        <!-- 数据表格 -->
        <div class="table-container">
            <!-- 操作按钮 -->
            <div class="action-button-container">
                <el-row :gutter="5">
                    <el-col :span="1.5">
                        <el-button  size="small" icon="Refresh" type="primary" plain @click="refreshHandler">刷新</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button  size="small" icon="Plus" type="primary" plain @click="addHandler">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button  size="small" icon="Download" type="warning" plain>导出</el-button>
                    </el-col>
                </el-row>
            </div>

            <el-table :data="tableData" row-key="id" border style="width: 100%" default-expand-all
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                <el-table-column type="index" label="序号" width="60" header-align="center"
                    align="center"></el-table-column>
                <el-table-column prop="code" label="编码" width="180" header-align="center"
                    :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="name" label="名称" width="150" header-align="center" align="center"
                    :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="status" label="状态" width="80" header-align="center" align="center"
                    :show-overflow-tooltip="true">
                    <template #default="{ row }">
                        <el-switch v-model="row.status" :active-value="1" :inactive-value="0"
                            @change="handleSwitchChange(row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间" header-align="center" align="center" width="180"
                    :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="createdBy" label="创建人" header-align="center" align="center" width="120"
                    :show-overflow-tooltip="true"> </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button link icon="Edit" type="primary" size="small" @click="editHandler(scope.row)">编辑</el-button>
                        <el-button link icon="Delete" type="primary" v-if="(!scope.row.children || scope.row.children.length <= 0)" size="small"
                             @click="deleteHandler(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="form.open" :title="form.title" width="500px" append-to-body center>
            <el-form ref="formRef" :model="form.data" :rules="form.rules" label-width="auto">
                <el-form-item label="编码" prop="code">
                    <el-input v-model="form.data.code"></el-input>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.data.name"></el-input>
                </el-form-item>
                <el-form-item label="上级部门" prop="parentId">
                    <el-tree-select v-model="form.data.parentId" :data="tableData"
                        :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id"
                        placeholder="选择上级部门" clearable check-strictly />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <dictselection v-model="form.data.status" classCode="system:Status" :dictData="statsDic">
                    </dictselection>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="form.open = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import dictselection from '@/components/DictExtend/DictSelectionWithData.vue';
import msgHelper from '@/util/msgHelper.js'
import orgapi from '@/api/system/org'
import dictApi from "@/api/system/dict.js"
import dictTag from '@/components/DictExtend/DictDataTagForTableItem.vue';

const tableData = ref([]); // 表格数据
const queryInputModel = ref({ code: '', name: '', status: null }); // 查询条件
const statsDic = ref([]);

const form = ref({
    open: false,
    title: '新增',
    data: {
        id: undefined,
        code: '',
        name: '',
        parentId: '',
        status: 1,
    },
    rules: {
        code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    },
});

// 加载数据
const loadData = async () => {
    try {
        const res = await orgapi.getTree(queryInputModel.value);
        tableData.value = res.data.data;
    } catch (error) {
        msgHelper.showError('加载数据失败');
    }
};

// 刷新数据
const refreshHandler = () => {
    loadData();
};

// 清空查询条件
const resetQueryInputHandler = () => {
    queryInputModel.value = { code: '', name: '', status: null };
};

// 新增
const addHandler = () => {
    retSetFrom();
    form.value.data.id = undefined;
    form.value.title = "新增";
    form.value.open = true;


};

const retSetFrom = () => {
    form.value.data = {
        id: undefined, code: undefined, name: undefined,
        parentId: undefined, status: 1
    };
}

// 编辑
const editHandler = (row) => {
    retSetFrom()
    orgapi.getById({ id: row.id }).then(res => {
        if (res.data.success) {
            form.value.data = res.data.data;
            form.value.open = true;
            form.value.title = "编辑";
        }
        else {
            msgHelper.show("获取数据失败" + res.data.msg);
        }
    });
};

// 删除
const deleteHandler = async (row) => {
    try {
        await orgapi.del({ id: row.id, version: row.version });
        msgHelper.show('删除成功');
        loadData();
    } catch (error) {
        msgHelper.showError('删除失败');
    }
};

// 提交表单
const submitForm = async () => {
    if (form.value.data.id) {
        await orgapi.update(form.value.data);
        msgHelper.show('更新成功');
    } else {
        await orgapi.add(form.value.data);
        msgHelper.show('新增成功');
    }
    form.value.open = false;
    loadData();

};

onMounted(async () => {
    const Sres = await dictApi.getDataByCode("System:Status");
    if (Sres.data && Sres.data.data) {
        statsDic.value = Sres.data.data;
    };
});
const handleSwitchChange = async (row) => {
    await orgapi.setStatus({ id: row.id, status: row.status, version: row.version })
        .then(res => {
            if ( res.data.success) {
                msgHelper.show('更新成功');
                loadData();
            }
            else {
                msgHelper.showError('更新失败');
            }
        })
        .catch(error => {
            msgHelper.showError('更新失败');
        });
}
</script>

<style scoped></style>